﻿using System;
using System.IO;
using System.Text;

namespace Blackbird.Common.Logging
{
    public class FileLogger : ILogEntryReceiver, IDisposable
    {
        private string _filename;
        private FileStream _logFile;

        private string _name;

        public FileLogger(string name)
        {
            Name = name; // Name setter has a sie efect of creating the filename;

            _logFile = File.Create(_filename);
        }

        #region IDisposable Members

        public void Dispose()
        {
            _logFile.Flush();
            _logFile.Close();
            _logFile.Dispose();
        }

        #endregion

        #region ILogEntryReceiver Members

        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                _filename = string.Format("{0}_{1}.{2}", _name, "log", ".log");
            }
        }

        public LogEntryType Level { get; set; }

        public void Clear()
        {
            _logFile.Close();
            File.Delete(_filename);

            _logFile = File.Create(_filename);
        }

        public void LogMessage(LogEntry entry)
        {
            string logMessage = string.Concat(entry.ToString(), "\r\n");
            byte[] messageBytes = Encoding.ASCII.GetBytes(logMessage.ToCharArray(), 0, logMessage.Length);
            _logFile.BeginWrite(messageBytes, 0, messageBytes.Length, WriteFinish, null);
        }

        public void Refresh()
        {
            //Ignore refresh since we're writing to a file instead of a screen.
        }

        #endregion

        private void WriteFinish(IAsyncResult ar)
        {
        }
    }
}